﻿using NewLife;
using NewLife.Collections;
using NewLife.Data;
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Serialization;

namespace Zdap.XCode
{
    public class Pager : PageParameter
    {
        public class __
        {
            /// <summary>排序字段</summary>
            public string Sort = "Sort";

            /// <summary>是否降序</summary>
            public string Desc = "Desc";

            /// <summary>页面索引</summary>
            public string PageIndex = "PageIndex";

            /// <summary>页面大小</summary>
            public string PageSize = "PageSize";
        }

        /// <summary>名称类。用户可根据需要修改Url参数名</summary>
        [XmlIgnore, ScriptIgnore]
        public static __ _ = new __();

        /// <summary>
        /// 参数集合 多个条件 And
        /// 说明：
        /// 时间段查询：格式如下：{
        ///    "params": {
        ///        "between#": {
        ///            "createTime": [
        ///                "2023-02-15",
        ///                "2023-02-16"
        ///            ]}}}
        ///            其中：between# 为特殊标识字段名称，createTime为字段名称 ，
        ///            生成的查询语句如下：
        ///            Select * From 表名称 Where createTime 大于等于 '2023-02-15 00:00:00' And createTime 小于 '2023-02-16 00:00:00'
        /// </summary>
        [XmlIgnore, ScriptIgnore]
        public IDictionary<string, object> Params { get; set; } = new NullableDictionary<string, object>(StringComparer.OrdinalIgnoreCase);

        /// <summary>是否返回列头</summary>
        [XmlIgnore, ScriptIgnore]
        public bool ReturnColumn { get; set; } = false;

        //private static readonly PageParameter _def = new PageParameter();

        ///// <summary>默认参数。如果分页参数为默认参数，则不参与构造Url</summary>
        //[XmlIgnore, ScriptIgnore]
        //public PageParameter Default { get; set; } = _def;
        public Pager()
        {
        }

        public object this[string key]
        {
            get
            {
                if (key.EqualIgnoreCase(_.Desc))
                    return Desc + "";
                else if (key.EqualIgnoreCase(_.PageIndex))
                    return PageIndex + "";
                else if (key.EqualIgnoreCase(_.PageSize))
                    return PageSize + "";

                // 为了布尔型取空字符串时得到null。var enable = p["enable"]?.ToBoolean()
                var v = Params[key];
                if (v == null || v is string && v == string.Empty)
                    return null;

                return v;
            }
            set
            {
                if (key.EqualIgnoreCase(_.Desc))
                    Desc = value.ToBoolean();
                else if (key.EqualIgnoreCase(_.PageIndex))
                    PageIndex = value.ToInt();
                else if (key.EqualIgnoreCase(_.PageSize))
                    PageSize = value.ToInt();
                else
                    Params[key] = value;
            }
        }
    }
}